package org.singledog.form.builder.dataset;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ClassPathResource;

import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class DataSetMetaReader {

    private static final Map<String, DataSetMeta> datasetMetaMap = new ConcurrentHashMap<>();

    public static DataSetMeta getDataSetMeta(String path) {
        DataSetMeta meta = datasetMetaMap.get(path);
        if (meta == null) {
            meta = buildDataSetMeta(path);
            if (meta != null) {
                datasetMetaMap.put(path, meta);
            }
        }

        return meta;
    }

    public static DataSetMeta buildDataSetMeta(String path) {
        ClassPathResource resource = new ClassPathResource(path);
        if (resource.exists() && resource.isReadable()) {
            try (InputStream is = resource.getInputStream()) {
                String json = IOUtils.toString(is, "UTF-8");
                DataSetMeta meta = JSON.parseObject(json, DataSetMeta.class);
                return meta;
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        } else {
            log.error("dataset path {} not exists or can't read !", path);
        }

        return null;
    }

}
